package com.hmh.DAO.Mappers;

import com.hmh.Entities.BlogState;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.BIT)
public class BlogStateTypeHandler extends BaseTypeHandler<BlogState> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, BlogState blogState, JdbcType jdbcType) throws SQLException {
        ps.setByte(i,blogState2Byte(blogState));
    }

    @Override
    public BlogState getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return byte2BlogState(rs.getByte(columnName));
    }

    @Override
    public BlogState getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return byte2BlogState(rs.getByte(columnIndex));
    }

    @Override
    public BlogState getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return byte2BlogState(cs.getByte(columnIndex));
    }
    private byte blogState2Byte(BlogState blogState){
        switch (blogState){
            case ACTIVE -> {
                return 1;
            }
            case CLOSED -> {
                return 0;
            }
            case INACTIVE -> {
                return 2;
            }
            default -> {
                return -1;
            }
        }
    }
    private BlogState byte2BlogState(Byte b){
        switch (b){
            case 0 -> {
                return BlogState.CLOSED;
            }
            case 1 -> {
                return BlogState.ACTIVE;
            }
            case 2 -> {
                return BlogState.INACTIVE;
            }
            default -> {
                return null;
            }
        }
    }
}